﻿"use strict";

function Sample()
{
    // Private variables
    var SAMPLE_LASTFPS = 0;
    var SAMPLE_START = 0;
    var SAMPLE_TIMINGS = {};
    var SAMPLE_LASTTIME = new Date().getTime();
    var SAMPLE_INTERVAL = 1000;
    var SAMPLE_NEXTTIME = new Date().getTime() + SAMPLE_INTERVAL;
    var that = this;

    // Public methods
    this.Percent = function (namespace, event) {
        var key = namespace + "_" + event;
        var entry = SAMPLE_TIMINGS[key];
        if (!entry)
            return 0;
        var length = entry[0];
        var ctr = entry[1];
        var total = 0;
        for (var key in SAMPLE_TIMINGS)
            total += SAMPLE_TIMINGS[key][0];
        var percent = length * 100 / total;
        return percent;
    }
    this.Dump = function () {
        // Dump the timings		
        var tuples = [];
        var total = 0;
        for (var key in SAMPLE_TIMINGS) {
            tuples.push([key, SAMPLE_TIMINGS[key]]);
            total += SAMPLE_TIMINGS[key][0];
        }
        tuples.sort(function (a, b) {
            a = a[1][0];
            b = b[1][0];
            return a < b ? -1 : (a > b ? 1 : 0);
        });
        log("TOTAL TIME: " + total + "  ENGINE SPEED: " + engine.speed + "  FPS: " + engine.fps + "  USEANIMFRAME: " + window.useanimframe);
        for (var i = 0; i < tuples.length; i++) {
            var name = tuples[i][0].padright(' ', 40);
            var length = tuples[i][1][0].padleft(' ', 4);
            var ctr = tuples[i][1][1].padleft(' ', 4);
            var average = (length / ctr).decimal(4, 6);
            var percent = (length * 100 / total).decimal(2, 6);
            log(name + ' ' + '   length: ' + length + '   count: ' + ctr + '   avg ms: ' + average + '   percent: ' + percent + '%');
        }
        that.Clear();
    }
    this.Label = function (namespace, event) {
        var now = new Date().getTime();
        var key = namespace + "_" + event;
        if (SAMPLE_START == 0)
            SAMPLE_START = now;
        if (!(key in SAMPLE_TIMINGS))
            SAMPLE_TIMINGS[key] = [0, 0];
        var elapsed = now - SAMPLE_LASTTIME;
        var entry = SAMPLE_TIMINGS[key];
        entry[0] += elapsed;
        entry[1] += 1;
        SAMPLE_LASTTIME = now;
        if (now > SAMPLE_NEXTTIME) {
            SAMPLE_NEXTTIME = now + SAMPLE_INTERVAL;
            if (engine.dumpsamples)
                this.Dump();
        }
    }
    this.Clear = function () {
        SAMPLE_TIMINGS = {};
    }
}

